<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\FundsRecord;
use app\common\model\MeridConfig;
use app\common\model\RebateRecord;
use app\common\model\UserCoupon;
use app\common\model\WebMail;
use app\common\model\Withdraw;
use fast\Random;
use think\Db;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
	
	protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third', 'weixinlogin'];
	protected $noNeedRight = '*';
	
	public function _initialize()
	{
		parent::_initialize();
	}
	
	/**
	 * 会员中心
	 */
	public function index()
	{
		
		$userId = $this->auth->id;
		
		$model = new \app\admin\model\User();
		$userInfo = $model->getRelationInfo($userId);
		
		$orderModel = new \app\common\model\Order();
		
		//根据订单状态分类统计
		$orderCount = Db::name('order')
			->where(['user_id' => $userId])
			->group('order_status ASC')
			->column('count(id) as numbers', 'order_status');
		
		//统计已签收未评价订单
		$commnetCount = Db::name('order')
			->where([
				'user_id' => $userId,
				'order_status' => $orderModel::STATUS_SIGN,
				'comment_status' => 0,
				'deleted' => 0,
				])
			->count();
		
		//统计未完成售后
		$afterCount = Db::name('afterSales')
			->where(['user_id' => $userId, 'status' => ['neq', \app\common\model\AfterSales::STATUS_FINISH]])
			->count();
		
		$orderData = [
			'wait_pay' => isset($orderCount[1])?$orderCount[1]:0,
			'wait_delivery' => isset($orderCount[2])?$orderCount[2]:0,
			'wait_sign' => isset($orderCount[3])?$orderCount[3]:0,
			'comment' => $commnetCount,
			'after' => $afterCount,
		];
		
		$mer = Db::name('admin')
			->order(['id' => 'ASC'])
			->find();
		
		$code  = [
            "title" => $mer['nickname'],
            "content" => "",
            "url" => $this->request->domain().url('/mobile/user/register',['rmobile' => $userInfo['mobile']])
		];
		
		$notices = Db::name('Article')
			->where(['category_id' => 14])
			->field('id, title as name, category_id, cover_image, content, from_unixtime(create_time) as time')
			->select();
		
		$webMailNumber = Db::name('webMail')
			->where(['user_id' => $userId, 'status' => WebMail::STATUS_W])
			->count();
		
		//提现统计
		$userInfo['withdraw_count'] = Db::name('withdraw')
			->where(['user_id' => $userId, 'status' => Withdraw::STATUS_Y])
			->sum('amount');
		
		$fundsModel = new FundsRecord();
		//累计收益
		$userInfo['earnings_count'] = $fundsModel
			->where(['user_id' => $userId, 'type' => ['in', [$fundsModel::TYPE_REBATE, $fundsModel::TYPE_VOUCHER_REBATE]]])
			->sum('amount');
		
		//待返利
		$userInfo['wait_rebate'] = Db::name('rebateRecord')
			->where(['user_id' => $userId, 'status' => RebateRecord::STATUS_W])
			->sum('amount');
		
		//关于我们
		$about = Db::name('article')
			->where(['category_id' => 15])
			->find();
		$about && $about['url'] = $this->request->domain().url('/mobile/article/detail',['id'=> $about['id'],'source' => 'app']);
		
		//新手指引
		$help = Db::name('article')
			->where(['category_id' => 21])
			->find();
		$help && $help['url'] = $this->request->domain().url('/mobile/article/detail',['id'=> $help['id'],'source' => 'app']);
		
		
		$returnData = [
			'userInfo' => $userInfo,
			'orderCount' => $orderData,
			'notices' => $notices,
			'code' => $code,
			'feedback_url' => $this->request->domain().url('/mobile/feedback/index',['token'=>$this->auth->getToken(),'source' => 'app']),
			'aftersale_url' => $this->request->domain().url('/mobile/aftersales/index',['token'=>$this->auth->getToken(),'source' => 'app']),
			'web_mail_number' => $webMailNumber,
			'shop_status' => $userInfo['level'] >= \app\admin\model\User::LEVEL_2 ? 1 : 0,
			'shop_tips' => '购买会员商品或代理商品才能开店',
			'about' => $about,
			'help' => $help,
			'about_url' => $about['url']
		];
		$this->success('', $returnData);
	}
	
	/**
	 * 会员登录
	 *
	 * @param string $account 账号
	 * @param string $password 密码
	 */
	public function login()
	{
		$account = $this->request->request('account');
		$password = $this->request->request('password');
		$weixinId = input('post.weixin_id');
		if (!$account || !$password) {
			$this->error(__('Invalid parameters'));
		}
		$ret = $this->auth->login($account, $password);
		if ($ret) {
			
			//如果在传微信信息ID，绑定用户
			if($weixinId) {
				Db::name('weixinInfo')
					->where(['id' => $weixinId])
					->update(['user_id' => $this->auth->id]);
			}
			
			$model = new \app\admin\model\User();
			$data['userinfo'] = $model->getRelationInfo($this->auth->id);
			
			
			//配置数据
			$versionConfig = Db::name('meridConfig')
				->field('appstore_version')
				->find();
			
			$mobiltType = input('post.mobileType');
			$version = input('post.version');
			
			$data['appstore_version'] = 1;
			//如果ios传过来的版本号跟设置的审核版本号一致，那么是审核版本，否则为正式版本
			if($versionConfig && $versionConfig['appstore_version'] == $version && $mobiltType == 'ios') {
				$data['appstore_version'] = 0;
			}
			
			$this->success(__('Logged in successful'), $data);
		} else {
			$this->error($this->auth->getError());
		}
	}
	
	/**
	 * 手机验证码登录
	 *
	 * @param string $mobile 手机号
	 * @param string $captcha 验证码
	 */
	public function mobilelogin()
	{
		$mobile = $this->request->request('mobile');
		$captcha = $this->request->request('captcha');
		if (!$mobile || !$captcha) {
			$this->error(__('Invalid parameters'));
		}
		if (!Validate::regex($mobile, "^1\d{10}$")) {
			$this->error(__('Mobile is incorrect'));
		}
		$res = Sms::check($mobile, $captcha, 'mobilelogin');
		if ($res !== true) {
			$this->error($res);
		}
		$userModel = new \app\common\model\User();
		$user = $userModel->where(['mobile' => $mobile])->find();
		if ($user) {
			//如果已经有账号则直接登录
			$ret = $this->auth->direct($user->id);
		} else {
			$ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
		}
		if ($ret) {
			Sms::flush($mobile, 'mobilelogin');
			$data = ['userinfo' => $this->auth->getUserinfo()];
			$this->success(__('Logged in successful'), $data);
		} else {
			$this->error($this->auth->getError());
		}
	}
	
	/**
	 * 注册会员
	 * @param string $recommendMobile 推荐人手机号
	 * @param string $username 用户名
	 * @param string $password 密码
	 * @param string $pay_password 支付密码
	 * @param integer $code 短信验证码
	 * @param string $email 邮箱
	 * @param string $mobile 手机号
	 */
	public function register()
	{
		
		$postData = input('post.');
		$val = validate('User');
		
		if(!$postData['username']) {
			$postData['username'] = $postData['mobile'];
		}
		if (!$val->check($postData)) {
			$this->error($val->getError());
		}
		
		//验证是否需要推荐人
		$postData['recommend_id'] = '';
		
		//查找是否需要输入推荐人
		$configRow = Db::name('meridConfig')
			->field('reg_need_recommend')
			->find();
		
		$parent_path = '';
		if ($configRow && $configRow['reg_need_recommend'] == MeridConfig::NEED_RECOMMEND_Y) {
			if (!isset($postData['recommend_mobile']) || empty($postData['recommend_mobile'])) {
				$this->error('请输入推荐人手机号');
			}
		}
		if(isset($postData['recommend_mobile']) && $postData['recommend_mobile']) {
			
			$recommend = Db::name('user')->alias('u')
				->join('agent a', 'u.id = a.user_id', 'left')
				->where(['u.mobile' => $postData['recommend_mobile'], 'u.status' => 1])
				->field('u.id, u.parent_path, u.agent_user_id, a.id as agent_id')
				->find();
			if (!$recommend) {
				$this->error('推荐人不存在');
			}
		
			unset($postData['recommend_mobile']);
			$postData['recommend_id'] = $recommend['id'];
			
			//如果推荐人是代理商，那么新用户代理商就是推荐人，否则如果推荐人有归属代理，那么新用户和推荐人同一个代理
			if($recommend['agent_id']) {
				$postData['agent_user_id'] = $recommend['id'];
			} elseif ($recommend['agent_user_id']) {
				$postData['agent_user_id'] = $recommend['agent_user_id'];
			}
			
			//生成所有上级路径
			if($recommend['parent_path']){
				$parent_path = $recommend['parent_path'].','.$recommend['id'];
			} else {
				$parent_path = $recommend['id'];
			}
		}
		//检验验证码
		$codeRes = \app\common\library\Sms::check($postData['mobile'], $postData['code'], 'register');
		if (!$codeRes) {
			$this->error('验证码不正确');
		}
		
		unset($postData['code']);
		$pararms = [
			'pay_password' => isset($postData['pay_password'])?$postData['pay_password']:'',
			'recommend_id' => $postData['recommend_id'],
			'parent_path' => $parent_path,
			'agent_user_id' => isset($postData['agent_user_id'])? $postData['agent_user_id'] : ''
		];
		$ret = $this->auth->register($postData['username'], $postData['password'], '', $postData['mobile'], $pararms);
		if ($ret) {
			//如果在传微信信息ID，绑定用户
			if(input('post.weixin_id')) {
				Db::name('weixinInfo')
					->where(['id' => input('post.weixin_id')])
					->update(['user_id' => $this->auth->id]);
			}
			
			$data = ['userinfo' => $this->auth->getUserinfo()];
			$this->success(__('Sign up successful'), $data);
		} else {
			$this->error('注册出错，'.$this->auth->getError());
		}
	}
	
	/**
	 * 注销登录
	 */
	public function logout()
	{
		$this->auth->logout();
		$this->success(__('Logout successful'));
	}
	
	/**
	 * 修改会员个人信息
	 *
	 * @param string $avatar 头像地址
	 * @param string $username 用户名
	 * @param string $nickname 昵称
	 * @param string $bio 个人简介
	 */
	public function profile()
	{
		$user = $this->auth->getUser();
		$username = $this->request->request('username');
		$nickname = $this->request->request('nickname');
		$bio = $this->request->request('bio');
		$avatar = $this->request->request('avatar');
		$gender = $this->request->request('sex');
		$email = $this->request->request('email');
		
		if($username) {
			$exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
			if ($exists) {
				$this->error('用户名已经存在');
			}
		}
		$username && $user->username = $username;
		$nickname && $user->nickname = $nickname;
		$bio && $user->bio = $bio;
		$avatar && $user->avatar = $avatar;
		$gender && $user->gender = $gender;
		$email && $user->email = $email;
		$user->save();
		$this->success('修改成功');
	}
	
	/**
	 * 修改邮箱
	 *
	 * @param string $email 邮箱
	 * @param string $captcha 验证码
	 */
	public function changeemail()
	{
		$user = $this->auth->getUser();
		$email = $this->request->post('email');
		$captcha = $this->request->request('captcha');
		if (!$email || !$captcha) {
			$this->error(__('Invalid parameters'));
		}
		if (!Validate::is($email, "email")) {
			$this->error(__('Email is incorrect'));
		}
		if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
			$this->error(__('Email already exists'));
		}
		$result = Ems::check($email, $captcha, 'changeemail');
		if (!$result) {
			$this->error(__('Captcha is incorrect'));
		}
		$verification = $user->verification;
		$verification->email = 1;
		$user->verification = $verification;
		$user->email = $email;
		$user->save();
		
		Ems::flush($email, 'changeemail');
		$this->success();
	}
	
	/**
	 * 修改手机号
	 *
	 * @param string $email 手机号
	 * @param string $captcha 验证码
	 */
	public function changemobile()
	{
		$user = $this->auth->getUser();
		$mobile = $this->request->request('mobile');
		$captcha = $this->request->request('code');
		if (!$mobile || !$captcha) {
			$this->error(__('Invalid parameters'));
		}
		if (!Validate::regex($mobile, "^1\d{10}$")) {
			$this->error(__('Mobile is incorrect'));
		}
		
		if (\app\common\model\User::where('mobile', $mobile)
			->where('id', '<>', $user->id)
			->find()) {
			$this->error(__('Mobile already exists'));
		}
		
		$sms = new \app\common\library\Sms();
		$result = $sms::check($mobile, $captcha, 'changemobile');
		if ($result !== true) {
			$this->error($result);
		}
		$verification = $user->verification;
		$verification->mobile = 1;
		$user->verification = $verification;
		$user->mobile = $mobile;
		$user->save();
		
		$sms::flush($mobile, 'changemobile');
		$this->success();
	}
	
	/**
	 * 第三方登录
	 *
	 * @param string $platform 平台名称
	 * @param string $code Code码
	 */
	public function third()
	{
		$url = url('user/index');
		$platform = $this->request->request("platform");
		$code = $this->request->request("code");
		$config = get_addon_config('third');
		if (!$config || !isset($config[$platform])) {
			$this->error(__('Invalid parameters'));
		}
		$app = new \addons\third\library\Application($config);
		//通过code换access_token和绑定会员
		$result = $app->{$platform}->getUserInfo(['code' => $code]);
		if ($result) {
			$loginret = \addons\third\library\Service::connect($platform, $result);
			if ($loginret) {
				$data = [
					'userinfo' => $this->auth->getUserinfo(),
					'thirdinfo' => $result
				];
				$this->success(__('Logged in successful'), $data);
			}
		}
		$this->error(__('Operation failed'), $url);
	}
	
	/**
	 * 重置密码
	 *
	 * @param string $mobile 手机号
	 * @param string $newpassword 新密码
	 * @param string $captcha 验证码
	 */
	public function resetpwd()
	{
		$postData = input('post.');
		$val = validate('User');
		$val->scene('resetpwd');
		if(!$val->check($postData)){
			$this->error($val->getError());
		}
		
		$userModel = new \app\common\model\User();
		$user = $userModel->where(['mobile' => $postData['mobile']])->find();
		if (!$user) {
			$this->error(__('User not found'));
		}
		$ret = \app\common\library\Sms::check($postData['mobile'], $postData['code'], 'resetpwd');
		if ($ret !== true) {
			$this->error($ret);
		}
		
		//模拟一次登录
		$this->auth->direct($user->id);
		$ret = $this->auth->changepwd($postData['password'], '', true);
		if ($ret) {
			$this->success(__('Reset password successful'));
		} else {
			$this->error($this->auth->getError());
		}
	}

	/**
	 * 我的下级
	 * @token 用户token
	 * @recommend_id 推荐人ID
	 * @page 分页
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
    public function sons(){
	
	    //类型1下级，2下下级，3下下下级
	    $type = input('post.type',1,'int');
	
	    //用户ID
	    $uid = input('post.user_id');
	
	    if($uid){
	    	$user = Db::name('user')
			    ->where(['mobile' => $uid])
			    ->find();
	    	!$user && $this->error('用户不存在');
	    	$userId = $user['id'];
	    } else {
	    	$userId = $this->auth->id;
	    }
	
	    if(!in_array($type,[1,2,3])){
		    $type = 1;
	    }
	
	    $sons = Db::name('user')->alias('u')
		    ->join('user r', 'u.recommend_id = r.id', 'left')
		    ->where('FIND_IN_SET(\''.$userId.'\', u.parent_path)')
		    ->field('u.id, u.id as user_id, u.username as user_name,from_unixtime(u.createtime) as time, u.mobile as  phone, u.level as grade, r.mobile as recommend, u.parent_path')
		    ->order(['u.createtime' => 'DESC'])
		    ->select();
	    
	    $data = [
	    	'level1_nums' => 0,
		    'level2_nums' => 0,
		    'level3_nums' => 0,
		    'recommend1_nums' => 0,
		    'recommend2_nums' => 0,
		    'recommend3_nums' => 0,
		    'users' => [],
		    'son1' => [],
		    'son2' => [],
		    'son3' => []
	    ];
	    
	    if($sons) {
	    	$levels = \app\admin\model\User::$_level;
	    	
	    	foreach ($sons as $son){
	    		$son['recommend'] = substr($son['recommend'], 0, 3).'****'.substr($son['recommend'], 7,4);
	    		$son['phone'] = substr($son['phone'], 0, 3).'****'.substr($son['phone'], 7,4);
	    		$son['grade_text'] = isset($levels[$son['grade']]) ? $levels[$son['grade']] : '';
	    		
	    		$parents = array_reverse(explode(',', $son['parent_path']));
	    		if(isset($parents[0]) && $parents[0] == $userId) {
	    			$data['level1_nums'] ++;
	    			if($son['grade'] > 0) {
	    				$data['recommend1_nums'] ++;
				    }
				    $data['son1'][] = $son;
				    if($type == 1) {
				    	$data['users'][] = $son;
				    }
			    }
			
			    if(isset($parents[1]) && $parents[1] == $userId) {
				    $data['level2_nums'] ++;
				    if($son['grade'] > 0) {
					    $data['recommend2_nums'] ++;
				    }
				
				    $data['son2'][] = $son;
				    if($type == 2) {
					    $data['users'][] = $son;
				    }
			    }
			    
			    if(isset($parents[2]) && $parents[2] == $userId) {
				    $data['level2_nums'] ++;
				    if($son['grade'] > 0) {
					    $data['recommend2_nums'] ++;
				    }
				
				    $data['son3'][] = $son;
				    if($type == 3) {
					    $data['users'][] = $son;
				    }
			    }
			    
	    		
		    }
	    }
	    
	    
	    $this->success('查询成功', $data);
    }
	
	
	/**
	 * 修改密码
	 */
    public function changePassword(){
    	$oldPassword = input('post.old_password');
    	$password = input('post.password');
    	$confirmPassword = input('post.confirm_password');
    	!$oldPassword && $this->error('原密码不能为空');
    	!$password && $this->error('新密码不能为空');
    	!$confirmPassword && $this->error('确认密码不能为空');
    	
    	if($password != $confirmPassword) {
    		$this->error('两次密码不一致');
	    }
	    
		$res = $this->auth->changepwd($password, $oldPassword, false);
	    if ($res) {
	    	$this->auth->direct($this->auth->id);
		    $this->success('更改成功',['token' => $this->auth->getToken()]);
	    } else {
		    $this->error($this->auth->getError());
	    }
    }
    
    /**
     * 修改支付密码
     */
    public function changePayPassword(){
	    $oldPassword = input('post.old_password');
	    $password = input('post.password');
	    $confirmPassword = input('post.confirm_password');
	    !$oldPassword && $this->error('原支付密码不能为空');
	    !$password && $this->error('新支付密码不能为空');
	    !$confirmPassword && $this->error('确认密码不能为空');
	
	    if($password != $confirmPassword) {
		    $this->error('两次密码不一致');
	    }
	    
	    if(!preg_match('/\d{6}/', $password)) {
	    	$this->error('支付密码为6位数字组成');
	    }
	
	    $userId = $this->auth->id;
	    $user = Db::name('user')->find($userId);
	    if($user['pay_password'] != $this->auth->getEncryptPassword($oldPassword, $user['salt'])) {
	    	$this->error('原密码不正确');
	    }
	    
	    $newPassword = $this->auth->getEncryptPassword($password, $user['salt']);
	    $res = Db::name('user')->where(['id' => $user['id']])->update(['pay_password' => $newPassword]);
	    if ($res !== false) {
		    $this->success('更改成功');
	    } else {
		    $this->error($this->auth->getError());
	    }
    }
	
	/**
	 * 实名认证
	 */
	public function authentication()
	{
		$userId = $this->auth->id;
		$trueName = input('post.true_name');
		$idCard = input('post.idcard');
		
		!$trueName && $this->error('真实姓名不能为空');
		!$idCard && $this->error('身份证号未填写');
		
		$preg = '/(^\d{18}$)|(^\d{15}$)|(^\d{17}(x|X|\d)$)/';
		if(!preg_match($preg, $idCard)){
			$this->error('身份证格式不正确');
		}
		
		$images = input('post.images');
		
		if(!$images && (!isset($_FILES['card_1']) || empty($_FILES['card_1']) || !isset($_FILES['card_2']) || empty($_FILES['card_2']) || !isset($_FILES['card_3']) || empty($_FILES['card_3']))){
			$this->error('3张图片必须上传');
		}

		
		$row = Db::name('userVerified')->where(['user_id' => $userId])->find();
		if($row && $row['status'] == 2){
			$this->error('您已经实名认证了');
		}
		
		$noRow = Db::name('userVerified')->where(['card_no' => $idCard, 'user_id' => ['neq', $userId]])->find();
		if($noRow){
			$this->error('该身份证号码已经绑定其它帐号');
		}
		
		//提交上传好图片的实名认证(小程序)
		if($images) {
			$img = explode(',', $images);
			if(count($img) != 3) {
				$this->error('三张图片必须上传');
			}
		} else {
			//需要上传图片的(APP)
			$img = [];
			$card1 = uploadImg('card_1', 'card');
			if($card1['status']){
				$img[] = $this->request->domain().DS.$card1['path'];
			} else {
				$this->error($card1['msg']);
			}
			
			$card2 = uploadImg('card_2', 'card');
			if($card2['status']){
				$img[] = $this->request->domain().DS.$card2['path'];
			} else {
				$this->error($card2['msg']);
			}
			
			$card3 = uploadImg('card_3', 'card');
			if($card3['status']){
				$img[] = $this->request->domain().DS.$card3['path'];
			} else {
				$this->error($card2['msg']);
			}
		}
		
		
		
		$data = [
			'user_id' => $userId,
			'true_name' => $trueName,
			'card_no' => $idCard,
			'images' => implode(',', $img),
			'create_time' => time(),
			'status' => 1,
			'remark' => '',
		];
		
		if($row){
			$res = Db::name('userVerified')->where(['id' => $row['id']])->update($data);
		} else {
			$res = Db::name('userVerified')->insert($data);
		}
		if($res !== false){
			$this->success('提交成功，等待审核');
		} else {
			$this->error('提交出错，请稍候重试');
		}
		
	}
	
	
	/**
	 * 重置支付密码
	 *
	 * @param string $mobile 手机号
	 * @param string $newpassword 新密码
	 * @param string $captcha 验证码
	 */
	public function resetPayPassword()
	{
		$password = input('post.password');
		$code = input('post.code');
		if(!$password || !$code) {
			$this->error('参数错误');
		}
		
		
		if(!preg_match('/\d{6}/', $password)) {
			$this->error('支付密码为6位数字组成');
		}
		
		$userId = $this->auth->id;
		$user = Db::name('user')->find($userId);
		
		$ret = \app\common\library\Sms::check($user['mobile'], $code, 'resetpwd');
		if ($ret !== true) {
			$this->error($ret);
		}
		
		
		$newPassword = $this->auth->getEncryptPassword($password, $user['salt']);
		$res = Db::name('user')->where(['id' => $user['id']])->update(['pay_password' => $newPassword]);
		if ($res !== false) {
			$this->success('操作成功');
		} else {
			$this->error($this->auth->getError());
		}
	}
	
	
	/**
	 * 用户优惠券
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function couponList(){
		$userId = $this->auth->id;
		$rows  = Db::name('userCoupon')->alias('c')
			->join('business b', 'c.business_id = b.id', 'left')
			->where(['c.user_id' => $userId])
			->order(['c.create_time'=> 'DESC'])
			->field('b.name as business_name, c.id, c.name, c.amount, c.min_amount, from_unixtime(c.start_time) as start_time, from_unixtime(c.end_time) as end_time, c.status')
			->select();
		
		$statusList = UserCoupon::$statusList;
		if($rows) {
			foreach($rows as $k => $row) {
				$rows[$k]['status_text'] = isset($statusList[$row['status']]) ? $statusList[$row['status']] : '';
			}
		}
		
		$this->success('查询成功', $rows);
	}
	
	/**
	 * 微信登录
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function weixinLogin(){
		$postData =input('post.');
		
		if(!isset($postData['unionid']) || empty($postData['unionid']) || !isset($postData['openid']) || !$postData['openid']) {
			$this->error('参数错误');
		}
		
		$unionId = $postData['unionid'];
		//查找数据是存已经存在
		$row = Db::name('weixinInfo')
			->where([
				'unionid' => $unionId,
				'type' => 1
			])
			->find();
		
		if(!$row) {
			$insertData = [
				'openid' => $postData['openid'],
				'nickname' => input('post.name'),
				'sex' => (isset($postData['gender']) && $postData['gender'] == '男')?1:2,
				'country' => isset($postData['country'])?$postData['country']:'',
				'province' => isset($postData['country'])?$postData['province']:'',
				'city' => isset($postData['city'])?$postData['city']:'',
				'headimgurl' => isset($postData['iconurl'])?$postData['iconurl']:'',
				'subscribe_time' => time(),
				'create_time' => time(),
				'update_time' => time(),
				'unionid' => $postData['unionid'],
				'type' => 1
			];
			
			$weixinId = Db::name('weixinInfo')->insertGetId($insertData);
			if($weixinId) {
				$this->success('添加信息成功', ['weixin_id' => $weixinId, 'userinfo' => ['id' => '']], 201);
			}
		} elseif(!$row['user_id']) {
			$this->success('请绑定用户', ['weixin_id' => $row['id'], 'userinfo' => ['id' => '']], 201);
		} else {
			$userId = $row['user_id'];
			$ret = $this->auth->direct($userId);
			$model = new \app\admin\model\User();
			$userInfo = $model->getRelationInfo($userId);
			$this->success('登录成功', ['weixin_id' => '', 'userinfo' => $userInfo]);
		}
	}
}
